package org.geektimes.projects.user.validator.bean.validation.validator;

import org.apache.commons.lang.StringUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.validator.bean.validation.annotation.PhoneNumber;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {

   private String regPattern;

   private int length;

   public void initialize(PhoneNumber constraint) {
      if (StringUtils.isBlank(constraint.pattern()))
         this.regPattern = "^(\\+?0?86)?1[345789]\\d{9}$";
      else {
         this.regPattern = constraint.pattern();
      }
      this.length = constraint.length();
   }

   public boolean isValid(String phoneNumber, ConstraintValidatorContext context) {
      Pattern p = Pattern.compile(regPattern);
      Matcher matcher = p.matcher(phoneNumber);
      return length == 11 && matcher.matches();
   }
}
